package com.freework.tree;

import java.util.ArrayList;

import java.util.List;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class RootlessTreeStructureService implements TreeStructureServiceI{

	
//	public static void main(String args[]){
//		TreeDatas treeData=new TreeDatas("1","0","a0101");
//		treeData.setCode("03");
//		TreeDatas treeData3=new TreeDatas("5","0","a0101");
//		treeData3.setCode("0203");
//		TreeDatas treeData1=new TreeDatas("2","1","a0101");
//		treeData1.setCode("0301");
//		TreeDatas treeData2=new TreeDatas("3","1","a0101");
//		treeData2.setCode("0302");
//		
//		
//		System.out.println(toBornTree1(Arrays.asList(treeData,treeData1,treeData2,treeData3), null));
//		
//		
//	}
	
	
	
	public   List toBornTree(List list1, Integer rootid){
		List<TreeDatas> list=list1;
		Map<Integer,List<TreeDatas>> data=new HashMap<Integer,List<TreeDatas>>();
		for (TreeDatas treeDatas : list) {
			List<TreeDatas> list2=data.get(treeDatas.getPid());
			if(list2==null){
				list2=new ArrayList<TreeDatas>();
				data.put(treeDatas.getPid(), list2);
			}
			list2.add(treeDatas);
		}
		for (TreeDatas treeDatas : list) {
			  
			List<TreeDatas> trees=data.get(treeDatas.getId());
			  if(trees!=null&&trees.size()>0){				  
				  treeDatas.setLeaf(false);
				  treeDatas.setChildren(trees);
				  data.remove(treeDatas.getId());
			  }
			
		}
		//System.out.println(data);
		
		Collection<List<TreeDatas>> root=data.values();
		
		List<TreeDatas> rootList = new ArrayList<TreeDatas>();
		for (List<TreeDatas> key : root) {
			rootList.addAll(key);
		}
		Collections.sort(rootList, treeCode);
		return rootList;
	}
	final static Comparator<TreeDatas> treeCode=new Comparator<TreeDatas>(){
		public int compare(TreeDatas o1, TreeDatas o2) {
			return o1.getCode().compareTo(o2.getCode());
		}
	};

	


}